package com.main.common.configs;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

/**
 * 加载語言包
 */
@Slf4j
@Configuration
public class MessageSourceConfig {

    @Bean(name = "messageSource")
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        String[] strings = scanModelsForI18nFolders();
        messageSource.setBasenames(strings);
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    public String[] scanModelsForI18nFolders() {
        try {
            // 通配规则 直接获取 Resources中的内容
            String resourcePattern = "classpath*:i18n/messages*.properties";
            ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resourcePatternResolver.getResources(resourcePattern);
            String[] paths = new String[resources.length];

            for (int i = 0; i < resources.length; i++) {
                Resource resource = resources[i];
                String[] urlStrArr = resource.getURL().toString().split("/");
                int index = urlStrArr.length - 1;
                String moduleName = urlStrArr[index];
                // 通配符加+ 模块名 + /国际化数据目录
                paths[i] = "classpath:i18n/" + moduleName.substring(0, moduleName.length() - 11);

                System.out.println(paths[i]);
            }
            return paths;

        } catch (Exception e) {
            log.info(e.getMessage());
        }
        return null;
    }
}
